package com.augn.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Data
@Component
public class TokenUtil {
    @Value("${token.privateKey}")
    private String privateKey;

    private String userId;


    // 加密token
    public String getToken(String account, String role) {
        //这个是放到负载payLoad 里面,魔法值可以使用常量类进行封装.
        String token = JWT
                .create()
                .withClaim("account" ,account)
                .withClaim("role", role)
                .withClaim("timeStamp", System.currentTimeMillis())
                .sign(Algorithm.HMAC256(privateKey));
        return token;
    }

    // 解析token
    public Map<String, String> parseToken(String token) {
        HashMap<String, String> map = new HashMap<>();
        DecodedJWT decodedjwt = JWT.require(Algorithm.HMAC256(privateKey))
                .build().verify(token);
        Claim userId = decodedjwt.getClaim("account");
        Claim userRole = decodedjwt.getClaim("role");
        Claim timeStamp = decodedjwt.getClaim("timeStamp");
        map.put("account", userId.asString());
        this.userId =userId.asString();
        map.put("role", userRole.asString());
        map.put("timeStamp", timeStamp.asLong().toString());
        return map;
    }
}

